<?php

class Userstudygroup extends Zend_Db_Table
{
    protected $_name = 'userstudygroup';
    
    public function checkExist($group_id,$user_id)
    {
        $select = $this->getAdapter();
        $prepare = $select->query('
                SELECT count(*) as all_records 
                FROM userstudygroup 
                WHERE studygroup_id="'.$group_id.'"
                AND user_id="'.$user_id.'"');
        $result = $prepare->fetchAll(Zend_Db::FETCH_ASSOC);
        return $result[0]['all_records'];
    }
    
    public function ClearLinks($group_id)
    {
        $select = $this->getAdapter();
        $prepare = $select->query('DELETE FROM userstudygroup 
                                   WHERE studygroup_id="'.(int)$group_id.'"');
    }
    
    public function getLinkedUser($group_id)
    {
        $select = $this->getAdapter();
        $prepare = $select->query('SELECT 
                                        user.id,
                                        first_name,
                                        last_name,
                                        email,
                                        phone,
                                        userstudygroup.created_at 
                                   FROM user
                                   INNER JOIN userstudygroup on userstudygroup.user_id = user.id
                                   and studygroup_id="'.(int)$group_id.'"');
        $result = $prepare->fetchAll();
        return $result;
    }
    
    public function LinkUser($group_id, $user_id)
    {
        $data = array(
                    'studygroup_id' => $group_id,
                    'user_id' => $user_id,
                    'created_at' => date('Y-m-d'));
        $this->insert($data);
    }
    
    public function UnlinkUser($group_id, $user_id)
    {
        $this->delete('studygroup_id = '.$group_id.' and user_id = '.$user_id);
    }
}